from django import http
from django.contrib.auth.backends import ModelBackend
from users.models import User

class UsernameMobileLogin(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user=User.objects.get(username=username)
        except Exception as e:
            user=None #如果直接return None，当执行这句时，下面的if not user 取不到user 这个变量，会无法正常执行
        if not user:
            try:
                user = User.objects.get(mobile=username)
            except Exception as e:
                return None
        #校验密码
        if user.check_password(password)==False:
            return None
        return user